package com.wens.ui.util

import android.content.Context
import android.graphics.PixelFormat
import android.view.Gravity
import android.view.View
import android.view.WindowManager


/**
 *  view的context不能是application的context，可以activity是,否则
 *  @exception android.view.WindowManager.BadTokenException
 *                  Unable to add window -- token null is not valid; is your activity running?
 *
 *  在activity finish 之前，需要调用
 *  @see dismiss(View) 方法，否则会有异常
 *  @exception android.view.WindowLeaked
 *                  Activity com.wens.ui.example.ExampleActivity has leaked window
 *                  com.wens.ui.view.RoundImageView{f4bb14b VFED..C.. ......ID 0,0-1080,2070}
 *                  that was originally added here
 */
object FloatWindowUtil {

    fun show(
        view: View,
        width: Int = WindowManager.LayoutParams.WRAP_CONTENT,
        height: Int = WindowManager.LayoutParams.WRAP_CONTENT,
        x: Int = 0,
        y: Int = 0,
        gravity: Int = Gravity.NO_GRAVITY,
        type: Int = WindowManager.LayoutParams.TYPE_APPLICATION
    ) {
        if (view.windowToken == null) {
            val windowManager: WindowManager? =
                view.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
            val layoutParams = WindowManager.LayoutParams(width, height)
            layoutParams.x = x
            layoutParams.y = y
            layoutParams.type = type
            layoutParams.flags =
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            layoutParams.format = PixelFormat.RGBA_8888
            layoutParams.gravity = gravity
            view.layoutParams = layoutParams
            windowManager?.addView(
                view,
                layoutParams
            )
        }
    }

    fun show(view: View, layoutParams: WindowManager.LayoutParams) {
        if (view.windowToken == null) {
            val windowManager: WindowManager? =
                view.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
            view.layoutParams = layoutParams
            windowManager?.addView(
                view,
                layoutParams
            )
        }
    }

    /**
     *  activity调用finish之前必须调用来释放未被销毁的window,否则会发生windowLake错误
     */
    fun dismiss(view: View) {
        if (view.windowToken != null) {
            val windowManager: WindowManager? =
                view.context.getSystemService(Context.WINDOW_SERVICE) as WindowManager?
            windowManager?.removeView(view)
        }
    }
}